using System;

namespace CL
{
    public struct  CLEntityRef<T> where T : CLEntity
    {

        private readonly long instanceId;
        private T entity;

        private CLEntityRef(T t)
        {
            if (t == null)
            {
                this.instanceId = 0;
                this.entity = null;
                return;
            }
            this.instanceId = t.InstanceId;
            this.entity = t;
        }

        private T UnWrap
        {
            get
            {
                if (this.entity == null)
                {
                    return null;
                }
                if (this.entity.InstanceId != this.instanceId)
                {
                    // 这里instanceId变化了，设置为null，解除引用，好让runtime去gc
                    this.entity = null;
                }
                return this.entity;
            }
        }

        public static implicit operator CLEntityRef<T>(T t)
        {
            return new CLEntityRef<T>(t);
        }

        public static implicit operator T(CLEntityRef<T> v)
        {
            return v.UnWrap;
        }
    }
}
